package com.uniview.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.uniview.base.BaseDao;
import com.uniview.entity.po.UserRole;
import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.Query;
import com.uniview.entity.vo.QueryBuilder;
import com.uniview.enums.EMatchMode;
/**
 * 
 * 用户授权数据库操作对象
 * @author Qingtian Lei
 *
 */
@Repository("userRoleDao")
public class UserRoleDao extends BaseDao<UserRole> {
	
	/**
	 * 保存用户授权
	 * @param userRole 用户授权对象
	 * @return
	 * @throws Exception
	 */
	public int saveUserRole(UserRole userRole) throws Exception{
		return (int)this.save(userRole);
	}
	
	public boolean saveUserRole(List<UserRole> list) throws Exception {
		if(!list.isEmpty()){
			for (UserRole ur : list) {
				this.save(ur);
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 检查成员是否存在
	 * @param userId
	 * @param labelsId
	 * @return
	 * @throws Exception
	 */
	public boolean checkUserRole (String userId) throws Exception{
		String hql = "select count(*) from UserRole u where u.userId = ?";
		int count = this.findTotalRow(hql, userId);
		if (count > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 删除用户授权
	 * @param urId 授权id
	 * @return
	 * @throws Exception
	 */
	public boolean deleteUserRole(int urId) throws Exception {
		return this.deleteById(urId);
	}
	
	/**
	 * 根据角色查找所有授权的用户
	 * @param rId  角色id
	 * @return
	 * @throws Exception
	 */
	public List<UserRole> findAllUserRoleByRid(int rId)throws Exception {
		QueryBuilder queryBuilder = new QueryBuilder(UserRole.class.getName());
		queryBuilder.add(new Query("roleId",EMatchMode.EQUAL,rId));
		return this.findListByQueryBuilder(queryBuilder);
	}
	
	/**
	 * 
	 * 分页查找授权的用户
	 * @param queryBuilder 条件对象
	 * @param pageSize 页数
	 * @param pageNo 每页显示记录数
	 * @return
	 * @throws Exception
	 */
	public Pager<UserRole> findUserRoleByPager(QueryBuilder queryBuilder,int pageSize,int pageNo) throws Exception{
		return this.findPagerByQueryBuilder(queryBuilder, pageNo, pageSize);
	}
	
	/**
	 * 获取授权用户的总记录数
	 * @return
	 * @throws Exception
	 */
	public Long getTotalRow() throws Exception{
		return this.findTotalRow();
	}
	
	public boolean delByUserIdAndRoleId(String userId, Integer roleId) throws Exception{
		String hql = "delete from UserRole WHERE userId=? AND roleId=?";
		return deleteByHql(hql, userId,roleId);
	}
	
}
